﻿//-----------------------------------------------------------------------
// <copyright file="ModuleManager.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace App.Modules
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using App.Exceptions;
    
    /// <summary>
    /// Class which manages application modules.
    /// </summary>
    public class ModuleManager
    {
        #region Fields - Private

        /// <summary>
        /// List of modules we are managing.
        /// </summary>
        private IList<Module> modules = new List<Module>();

        /// <summary>
        /// Dictionary of modules we have.
        /// </summary>
        private IDictionary<Type, Module> moduleDict = new Dictionary<Type, Module>();

        #endregion

        #region Methods - Public

        /// <summary>
        /// Called when the application is starting up.
        /// </summary>
        public void Startup()
        {
            foreach (Module module in this.modules)
            {
                module.Startup();
            }

            foreach (Module module in this.modules)
            {
                module.RegisterForMessages();
            }
        }

        /// <summary>
        /// Called when the application is shutting down.
        /// </summary>
        public void Shutdown()
        {
            IEnumerable<Module> reverseModules = this.modules.Reverse();

            foreach (Module module in reverseModules)
            {
                if (module.Started)
                {
                    module.UnregisterForMessages();
                }
            }

            foreach (Module module in reverseModules)
            {
                if (module.Started)
                {
                    module.Shutdown();
                }
            }
        }

        /// <summary>
        /// Called each time the application goes idle.
        /// </summary>
        public void Work()
        {
            foreach (Module module in this.modules)
            {
                module.Work();
            }
        }

        /// <summary>
        /// Add a module to the manager.
        /// </summary>
        /// <param name="module">Module to add.</param>
        public void Add(Module module)
        {
            if (module == null)
            {
                throw new ArgumentNullException("module", "Module must be non-null.");
            }

            Module existing = this.GetModule(module.GetType(), false);
            if (existing != null)
            {
                throw new InvalidOperationException("Cannot install the same module twice.");
            }

            module.Manager = this;
            this.modules.Add(module);
            this.moduleDict.Add(module.GetType(), module);
        }

        /// <summary>
        /// Given a type, see if we have a module in the manager that matches it.
        /// </summary>
        /// <param name="type">Type of module to look for.</param>
        /// <param name="failIfNotFound">If true, will throw an exception if a module is not found.</param>
        /// <returns>Returns the module if we have a type match or null if none was found.</returns>
        public Module GetModule(Type type, bool failIfNotFound = true)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type", "Type must be non-null.");
            }

            Module res = null;

            this.moduleDict.TryGetValue(type, out res);

            if (failIfNotFound && res == null)
            {
                throw new AppException("Unable to find module: " + type.Name);
            }

            return res;
        }

        /// <summary>
        /// Given a type, see if we have a module in the manager that matches it.
        /// </summary>
        /// <param name="failIfNotFound">If true, will throw an exception if a module is not found.</param>
        /// <typeparam name="T">Type of module we are looking for.</typeparam>
        /// <returns>Returns the module if we have a type match or null if none was found.</returns>
        public T GetModule<T>(bool failIfNotFound = true) where T : Module
        {
            return this.GetModule(typeof(T), failIfNotFound) as T;
        }

        #endregion
    }
}
